﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMS.Entities.Master;
using System.Data;

namespace SMS.DAL
{
    public class BranchDA : DAHelpers.BaseDA<Branch>
    {
        public override Branch SaveObject(string userName, Branch tObject)
        {
            try
            {
                dbHelper.AddParameter("@Branch_ID", tObject.Branch_ID);
                dbHelper.AddParameter("@Branch_Name", tObject.BranchName);
                dbHelper.AddParameter("@Branch_City", tObject.City.CityID);
                dbHelper.AddParameter("@Branch_BranchManager", tObject.BranchManager.SalesMan_ID);
                object objID = dbHelper.ExecuteScaler("USP_INS_UPDATE_BRANCH", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                if (Convert.ToInt32(objID) > 0)
                    tObject.Branch_ID = Convert.ToInt32(objID);
                LogActivity(userName, string.Format("Branch Saved with ID {0}", tObject.Branch_ID), tObject);
                return tObject;
            }
            catch (Exception ex)
            {
                LogException(userName, ex, tObject);
                throw new Exception("Error Occured while Saving Branch");
            }
        }

       
        public override List<Branch> SearchObject(string userName, string SearchText)
        {
            dbHelper.AddParameter("@Search_Text", SearchText);
            var reader = dbHelper.ExecuteReader("USP_SEARCH_BRANCH", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
            var result = new List<Branch>();
            while (reader.Read())
            {
                result.Add(GetBranch(reader));
            }
            return result;
        }

        private Branch GetBranch(IDataReader reader)
        {
            Branch branch = new Branch();
            branch.Branch_ID = reader.GetInt32(0);
            if (!reader.IsDBNull(1))
                branch.BranchName = reader.GetString(1);
            if (!reader.IsDBNull(2))
                branch.BranchManager = new Entities.SalesManDetail { SalesMan_ID = reader.GetInt32(2), SalesMan_Name=reader.GetString(3)};
            if (!reader.IsDBNull(4))
                branch.City = new Entities.City { CityID = reader.GetInt32(4), CityName=reader.GetString(5) };
            return branch;
        }


        public override bool DeleteObject(string userName, Branch tObject)
        {
            throw new NotImplementedException();
        }

        public override List<Branch> GetObjectList(string userName, DateTime fromDate, DateTime toDate)
        {
            throw new NotImplementedException();
        }
              
    }
}
